import { _decorator, Component, Sprite, Animation, UITransform, ERigidBody2DType, BoxCollider2D, Size, Vec2, RigidBody2D, view, AnimationClip, PolygonCollider2D, math, Label, sys, Widget } from 'cc';
import DataManager from '../Runtime/DataManager';
import { createUINode, getFrameAsset, loadAnimationClip, setRoleloadDir } from '../utils';
import { GamePlayer } from '../Role/GamePlayer';
import { CHARGING_NAME_ENUM, ENEMY_NAME_ENUM, GAME_MODE_ENUM, HELMET_NAME_ENUM, LEAPING_NAME_ENUM, PLAYER_ENUM } from '../../Enums';
import { DumbEnemy } from '../Npc/DumbEnemy';
import { StoneManager } from '../Property/StoneManager';
import { BrickManager } from '../Property/BrickManager';
import { HeavyManager } from '../Property/HeavyManager';
import { JellyManager } from '../Property/JellyManager';
import { BombManager } from '../Property/BombManager';
import { LurkerManager } from '../Property/LurkerManager';
import { ChargingEnemy } from '../Npc/ChargingEnemy';
import { HelmetEnemy } from '../Npc/HelmetEnemy';
import { LeapingEnemy } from '../Npc/LeapingEnemy';
import { AlphabetControl } from '../Role/AlphabetControl';
import { NumberControl } from '../Role/NumberControl';
import { FriutManager } from '../Property/FriutManager';
import { JoyStickManager } from '../UI/JoyStickManager';
import { JoyAttackManager } from '../UI/JoyAttackManager';
import { userStore } from '../service/user';
const { ccclass } = _decorator;
@ccclass('TileMapManager')
export class TileMapManager extends Component {
    private low_level: number = 0
    // 初始化地图
    async init() {
        if (DataManager.Instance.fire_clip == null) {
            DataManager.Instance.fire_clip = loadAnimationClip(DataManager.Instance.mapAssets, 'fire', AnimationClip.WrapMode.Loop).animation
        }
        if (DataManager.Instance.luker_clip == null) {
            DataManager.Instance.luker_clip = loadAnimationClip(DataManager.Instance.mapAssets, 'luker', AnimationClip.WrapMode.Loop).animation
            DataManager.Instance.luker_frame = loadAnimationClip(DataManager.Instance.mapAssets, 'luker', AnimationClip.WrapMode.Loop).frame
        }
        if (DataManager.Instance.brick_clip == null) {
            DataManager.Instance.brick_clip = loadAnimationClip(DataManager.Instance.mapAssets, 'brick', AnimationClip.WrapMode.Default).animation
        }
        if (DataManager.Instance.jelly_clip == null) {
            DataManager.Instance.jelly_clip = loadAnimationClip(DataManager.Instance.mapAssets, 'jelly', AnimationClip.WrapMode.Default).animation
        }
        if (DataManager.Instance.blast_clip == null) {
            DataManager.Instance.blast_clip = loadAnimationClip(DataManager.Instance.mapAssets, 'blast', AnimationClip.WrapMode.Normal).animation
        }
        this.loadEnemyAssets()
        this.getLowLevel()
        // setTimeout(() => {
        // 初始化地图
        this.createdGround()
        // }, 100)
    }
    // 加载怪物的素材
    loadEnemyAssets() {
        if (DataManager.Instance.dumbEnemyList.length == 0) {
            DataManager.Instance.dumbEnemyList = setRoleloadDir("dumb_enemy", ENEMY_NAME_ENUM)
        }
        if (DataManager.Instance.chargingEnemyList.length == 0) {
            DataManager.Instance.chargingEnemyList = setRoleloadDir("charging_enemy", CHARGING_NAME_ENUM)
        }
        if (DataManager.Instance.helmetEnemyList.length == 0) {
            DataManager.Instance.helmetEnemyList = setRoleloadDir("helmet_enemy", HELMET_NAME_ENUM)
        }
        if (DataManager.Instance.leapingEnemyList.length == 0) {
            DataManager.Instance.leapingEnemyList = setRoleloadDir("leaping_enemy", LEAPING_NAME_ENUM)
        }
    }
    // 获取低层级的总数
    getLowLevel() {
        const { levelInfo } = DataManager.Instance
        const mapInfo = levelInfo.levels
        let arr = [47, 54, 55, 56, 29, 45, 46]
        mapInfo.forEach((item: any[]) => {
            item.forEach((item1) => {
                if (arr.find(item2 => item2 == item1)) {
                    this.low_level++
                }
            })
        })
    }
    setSensorNode(name, sensorNode, col, row, reaches, tile_name) {
        const { width, height, position } = DataManager.Instance
        const tile = createUINode(`${name}-${reaches + 1}`)
        tile.setParent(sensorNode)
        if (tile_name.includes('lurker') || tile_name.includes('slide')) {
            tile.setSiblingIndex(0)
        } else {
            tile.setSiblingIndex(reaches + 1)
        }
        const transform = tile.getComponent(UITransform)
        const rigidBody2D = tile.addComponent(RigidBody2D)
        rigidBody2D.type = ERigidBody2DType.Static
        const boxCollider2D = tile.addComponent(BoxCollider2D)
        boxCollider2D.sensor = true
        boxCollider2D.size = new Size(width / 2, position / 3)
        boxCollider2D.offset = new Vec2(0, 20)
        transform.setContentSize(width, height - 4)
        tile.setPosition(col * width, -row * position - 45)
    }
    async createdGround() {
        DataManager.Instance.async_scence = []
        DataManager.Instance.async_scence.push({
            type: 'fraction', node: "fraction", player: DataManager.Instance.fractionNumber
        })
        const node = createUINode("mapInfo")
        node.setParent(this.node)
        const { levelInfo, width, height, position } = DataManager.Instance
        const mapInfo = levelInfo.levels
        DataManager.Instance.mapWidth = mapInfo[0].length * width
        DataManager.Instance.mapHeight = mapInfo.length * position
        let reaches = this.low_level
        DataManager.Instance.low_level = this.low_level
        let arr = [47, 54, 55, 56, 29, 46]
        const sensorNode = createUINode("sensorNode")
        sensorNode.setParent(this.node)
        sensorNode.setPosition(-(mapInfo[0].length * width) / 2 + width / 2, 1024 / 2 - position)
        const temp_node = createUINode("")
        temp_node.setParent(sensorNode)
        temp_node.setSiblingIndex(0)
        mapInfo.forEach((item: any[], row: number) => {
            item.forEach((item1, col: number) => {
                let name = this.getNodeName(item1)
                let node_name = name + row + '-' + col
                const tile = createUINode(node_name)
                tile.setParent(node)
                tile.setSiblingIndex(reaches + 1)
                this.setSensorNode(`sensor-${row + 1}-${col}`, sensorNode, col, row, reaches, node_name)
                if (!arr.find(item2 => item2 == item1)) {
                    reaches = reaches + 1
                }
                tile.setPosition(col * width, -row * position - 2.28)
                // 设置最高高度和最高宽度
                if (row == mapInfo.length - 1 && col == item.length - 1) {
                    DataManager.Instance.cameraBoundary = tile.getPosition()
                    let positionX = -view.getVisibleSize().width / 2 + width / 2
                    if (tile.getPosition().x < view.getVisibleSize().width) {
                        positionX = -(mapInfo[0].length * width) / 2 + width / 2
                    }
                    node.setPosition(positionX, view.getVisibleSize().height / 2 - position + 16)
                }
                if (name == 'enemy') {
                    tile.setPosition(col * width, -row * position - ((height - position) / 2))
                }
                if (item1 == 1) {
                    const stoneManager = tile.addComponent(StoneManager)
                    stoneManager.init()
                    DataManager.Instance.async_scence.push({ type: 'property', node: node_name, player: stoneManager })
                    return
                }
                if (item1 == 2) {
                    const heavyManager = tile.addComponent(HeavyManager)
                    heavyManager.init()
                    DataManager.Instance.async_scence.push({ type: 'property', node: node_name, player: heavyManager })
                    return
                }
                if (item1 == 3) {
                    const brickManager = tile.addComponent(BrickManager)
                    brickManager.init()
                    DataManager.Instance.async_scence.push({ type: 'property', node: node_name, player: brickManager })
                    return
                }
                if (item1 == 22) {
                    const jellyManager = tile.addComponent(JellyManager)
                    jellyManager.init()
                    DataManager.Instance.async_scence.push({ type: 'property', node: node_name, player: jellyManager })
                    return
                }
                if (item1 == 23) {
                    const bombManager = tile.addComponent(BombManager)
                    bombManager.init()
                    DataManager.Instance.async_scence.push({ type: 'property', node: node_name, player: bombManager })
                    return
                }
                // 哑巴怪物
                if (item1 == 21) {
                    const dumbEnemy = tile.addComponent(DumbEnemy)
                    dumbEnemy.init(DataManager.Instance.dumbEnemyList)
                    DataManager.Instance.enemyList.push(dumbEnemy)
                    DataManager.Instance.async_scence.push({ type: name, node: node_name, player: dumbEnemy })
                    return
                }
                // 骷髅怪物
                if (item1 == 24) {
                    const chargingEnemy = tile.addComponent(ChargingEnemy)
                    chargingEnemy.init(DataManager.Instance.chargingEnemyList)
                    DataManager.Instance.enemyList.push(chargingEnemy)
                    DataManager.Instance.async_scence.push({ type: name, node: node_name, player: chargingEnemy })
                    return
                }
                // 甲壳虫怪物
                if (item1 == 25) {
                    const helmetEnemy = tile.addComponent(HelmetEnemy)
                    helmetEnemy.init(DataManager.Instance.helmetEnemyList)
                    DataManager.Instance.enemyList.push(helmetEnemy)
                    DataManager.Instance.async_scence.push({ type: name, node: node_name, player: helmetEnemy })
                    return
                }
                // 会飞怪物
                if (item1 == 44) {
                    const leapingEnemy = tile.addComponent(LeapingEnemy)
                    leapingEnemy.init(DataManager.Instance.leapingEnemyList)
                    DataManager.Instance.enemyList.push(leapingEnemy)
                    DataManager.Instance.async_scence.push({ type: name, node: node_name, player: leapingEnemy })
                    return
                }
                // 绿色玩家
                if (item1 == 20) {
                    const gamePlayer = tile.addComponent(GamePlayer)
                    gamePlayer.init(PLAYER_ENUM.BLUE)
                    if (!sys.isMobile) {
                        const alphabetControl = gamePlayer.addComponent(AlphabetControl)
                        alphabetControl.init()
                    }
                    if(DataManager.Instance.gameMode==GAME_MODE_ENUM.ONLINE){
                        if(DataManager.Instance.room){
                            if(DataManager.Instance.room.ownerId==userStore().info.id){
                                DataManager.Instance.current_role=node_name
                            }
                        }
                    }
                    DataManager.Instance.player.push(gamePlayer)
                    DataManager.Instance.async_scence.push({ type: name, node: node_name, player: gamePlayer })
                    tile.setPosition(col * width, -row * position - ((height - position) / 2))
                    return
                }

                // 蓝色玩家
                if (item1 == 19) {
                    if (DataManager.Instance.gameMode != GAME_MODE_ENUM.SINGLE) {
                        const gamePlayer = tile.addComponent(GamePlayer)
                        gamePlayer.init(PLAYER_ENUM.GREEN)
                        if (!sys.isMobile) {
                            const numberControl = gamePlayer.addComponent(NumberControl)
                            numberControl.init()
                        }
                        if(DataManager.Instance.gameMode==GAME_MODE_ENUM.ONLINE){
                            if(DataManager.Instance.room){
                                if(DataManager.Instance.room.memberId==userStore().info.id){
                                    DataManager.Instance.current_role=node_name
                                }
                            }
                        }
                        DataManager.Instance.player.push(gamePlayer)
                        DataManager.Instance.async_scence.push({ type: name, node: node_name, player: gamePlayer })
                        tile.setPosition(col * width, -row * position - ((height - position) / 2))
                    }
                    return
                }
                // 空地
                if (item1 == 0) {
                    return
                }
                // 尖刺 45//快的尖刺
                if (item1 == 29 || item1 == 46 || item1 == 45) {
                    const lurkerManager = tile.addComponent(LurkerManager)
                    lurkerManager.init(name, item1 == 46 ? true : false)
                    tile.setSiblingIndex(0)
                    return
                }
                const transform = tile.getComponent(UITransform)
                transform.setContentSize(width, height)
                const rigidBody2D = tile.addComponent(RigidBody2D)
                rigidBody2D.type = ERigidBody2DType.Static
                // 水果
                if (name.includes('fruit')) {
                    const friutManager = tile.addComponent(FriutManager)
                    friutManager.init(item1)
                    DataManager.Instance.async_scence.push({ type: 'property', node: node_name, player: friutManager })
                    tile.setPosition(col * width, -row * position)
                    return
                }
                const boxCollider2D = tile.addComponent(BoxCollider2D)
                boxCollider2D.offset = new Vec2(0, -28)
                boxCollider2D.size = new Size(width, position)
                let sprite = tile.addComponent(Sprite)
                sprite.sizeMode = Sprite.SizeMode.CUSTOM
                // 滑块
                if (item1 == 47 || item1 == 55 || item1 == 56 || item1 == 54) {
                    tile.setSiblingIndex(0)
                    boxCollider2D.offset = new Vec2(0, 0)
                    transform.setContentSize(width, position)
                    if (sys.isMobile) {
                        boxCollider2D.size = new Size(.5, position / 2)
                    } else {
                        boxCollider2D.size = new Size(.5, .5)
                    }
                    boxCollider2D.sensor = true
                    tile.setPosition(col * width, -row * position - ((height - position) / 2))
                }
                // 火焰的墙壁
                if (item1 == 42 || item1 == 37) {
                    let png = item1 == 42 ? '13.png' : '5.png'
                    sprite.spriteFrame = getFrameAsset(DataManager.Instance.mapAssets, png).spriteFrame
                    const column = createUINode("column")
                    column.setParent(tile)
                    column.setScale(2.5, 2.5)
                    column.setPosition(0, -30)
                    let columnSprite = column.addComponent(Sprite)
                    columnSprite.sizeMode = Sprite.SizeMode.TRIMMED
                    columnSprite.spriteFrame = getFrameAsset(DataManager.Instance.mapAssets, '219.png').spriteFrame
                    const fire = createUINode("fire")
                    fire.setParent(tile)
                    const fireTransform = fire.getComponent(UITransform)
                    fireTransform.setContentSize(17 * 3, 23 * 3)
                    let fireSprite = fire.addComponent(Sprite)
                    fireSprite.sizeMode = Sprite.SizeMode.CUSTOM
                    const animation = fire.addComponent(Animation)
                    animation.defaultClip = DataManager.Instance.fire_clip
                    animation.play()
                    return
                }
                sprite.spriteFrame = getFrameAsset(DataManager.Instance.mapAssets, `${item1}.png`).spriteFrame
            })
        });
        this.setBackGround(node)
        let positionX = -view.getVisibleSize().width / 2 + width / 2
        if (DataManager.Instance.cameraBoundary.x < view.getVisibleSize().width) {
            positionX = -(mapInfo[0].length * width) / 2 + width / 2
        }
        sensorNode.setPosition(positionX, view.getVisibleSize().height / 2 - position + 16)
    }
    setBackGround(parent) {
        const node = createUINode("background")
        node.setParent(parent)
        node.setSiblingIndex(0)
        node.setPosition(DataManager.Instance.mapWidth / 2 - 75, -DataManager.Instance.mapHeight / 2 + 104)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(DataManager.Instance.mapWidth, DataManager.Instance.mapHeight)
        const sprite = node.addComponent(Sprite)
        sprite.type = Sprite.Type.TILED
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.mapAssets, '495.png').spriteFrame
    }
    // 设置物体层级
    async createdGroundSensor() {
        const { levelInfo, width, height, position } = DataManager.Instance
        const mapInfo = levelInfo.levels
        const sensorNode = createUINode("sensorNode")
        sensorNode.setParent(this.node)
        sensorNode.setPosition(-(mapInfo[0].length * width) / 2 + width / 2, 1024 / 2 - position)
        let reaches = this.low_level
        mapInfo.forEach((item: any[], row: number) => {
            item.forEach((item1: any, col: number) => {
                let name = `sensor${row + 1}-${item.length}-${col}`
                const tile = createUINode(name)
                tile.setParent(sensorNode)
                tile.setSiblingIndex(reaches + 1)
                reaches = reaches + 1
                const transform = tile.getComponent(UITransform)
                const rigidBody2D = tile.addComponent(RigidBody2D)
                rigidBody2D.type = ERigidBody2DType.Static
                const boxCollider2D = tile.addComponent(BoxCollider2D)
                boxCollider2D.sensor = true
                boxCollider2D.size = new Size(width / 2, position / 2)
                boxCollider2D.offset = new Vec2(0, 20)
                transform.setContentSize(width, height - 4)
                tile.setPosition(col * width, -row * position - 45)
            })
        });
        let positionX = -view.getVisibleSize().width / 2 + width / 2
        if (DataManager.Instance.cameraBoundary.x < view.getVisibleSize().width) {
            positionX = -(mapInfo[0].length * width) / 2 + width / 2
        }
        sensorNode.setPosition(positionX, view.getVisibleSize().height / 2 - position + 16)
    }
    generateEllipsePoints(a = 72, b = 38, n = 30) {
        let points = [];
        for (let i = 0; i < n; i++) {
            let angle = (2 * Math.PI / n) * i;
            let x = (Math.cos(angle) * a).toFixed(2);
            let y = (Math.sin(angle) * b).toFixed(2);
            points.push(new Vec2(Number(x), Number(y)));
        }
        return points;
    }
    // 获取物体分类
    getNodeName(item) {
        let label = {
            'wall': [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 30, 31, 32, 34, 35, 36, 37, 39, 213, 35, 42], //墙
            'lurker': [29, 45], //尖刺
            'lurkerTouch': [46], //尖刺
            'space': [0], //空地
            'fruit': [26, 27, 28, 48, 49, 50, 51, 52, 53], //水果
            'role': [20, 19],//玩家19,
            'stone': [1], //石头
            'heavy': [2],//大石头
            'brick': [3], //砖块
            "jelly": [22],//果冻
            "bomb": [23],//炸弹
            "enemy": [21, 24, 25, 44],//怪物
            "slide": [47, 54, 55, 56]//滑道
        }
        for (let i in label) {
            if (label[i].includes(item)) {
                return i
            }

        }
    }
}

